# -*- coding: utf-8 -*-
# api.py
# Copyright 2017 杭州网川教育科技有限公司. All rights reserved.

from flask import jsonify
from flask_restful import Resource
import logging
from json import encoder
from flask_restful import reqparse

encoder.FLOAT_REPR = lambda o: format(o, '.2f')

logger = logging.getLogger()


class ApiResource(Resource):
    parser = None
    get_querier = None
    post_querier = None

    @classmethod
    def set_resource(cls, parser=None, get_querier=None, post_querier=None):
        cls.parser = parser
        cls.get_querier = get_querier
        cls.post_querier = post_querier

    def get(self):
        if self.__class__.get_querier:
            args = self.__class__.parser.parse_args()
            logger.debug('get args: %s' % str(args))

            try:
                query = self.__class__.get_querier.build_query(args)
                res = self.__class__.get_querier.build_result(query)
                logger.debug('args: %s' % str(args))
            except Exception as ex:
                logger.error('error: %s' % ex, exc_info=True)
                res = {'message': str(ex)}
            return jsonify(res)
        else:
            return jsonify({'message': 'no GET handler binded'})

    def post(self):
        if self.__class__.post_querier:
            args = self.__class__.parser.parse_args()
            logger.debug('post args: %s' % str(args))
            try:
                query = self.__class__.get_querier.build_query(args)
                res = self.__class__.get_querier.build_result(query)
                logger.debug('args: %s' % str(args))
            except Exception as ex:
                logger.error('error: %s' % ex, exc_info=True)
                res = {'message': str(ex)}
            return jsonify(res)
        else:
            return jsonify({'message': 'no POST handler binded'})


class NetworkMonitoringResource(ApiResource):
    pass


network_match_parser = reqparse.RequestParser()
network_match_parser.add_argument('words', type=list, location='json')
network_match_parser.add_argument('insert_time', type=str, location='json')
network_match_parser.add_argument('time_interval', type=list, location='json')
